const TerserPlugin = require('terser-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const path = require('path')
const webpack = require('webpack')
const glob = require('glob')
const dllPath = 'public/assets/dll'
const isProd = process.env.NODE_ENV === 'production'

const generateDllReferences = function () {
  const manifests = glob.sync(`${path.resolve(dllPath)}/*.json`)
  /* 把所有dll打包的json文件配置进去 */
  const arr = manifests.map(file => {
    return new webpack.DllReferencePlugin({
      context: path.resolve(__dirname),
      manifest: file
    })
  })
  isProd && arr.push(new BundleAnalyzerPlugin())
  return arr
}

const minimizer = isProd ? [
  new TerserPlugin({
    // 采用多进程打包
    parallel: true,
    terserOptions: {
      compress: {
        warnings: false,
        drop_console: isProd,
        drop_debugger: isProd,
        pure_funcs: ['console.log']
      }
    }
  }),
  new UglifyJsPlugin({
    uglifyOptions: {
    // 删除注释
      output: {
        comments: false
      }
    }
  }),
  new OptimizeCSSAssetsPlugin({})
] : []
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')
module.exports = {
  configureWebpack: {
    optimization: {
      minimizer: minimizer,
      runtimeChunk: {
        name: 'manifest'
      },
      splitChunks: {
        /**
         * @description 拆包，将大的包拆分出来，打包出对应的name.js文件
         */
        cacheGroups: {
          utils: {
            name: 'chunk-utils',
            test: /[\\/]node_modules[\\/](core-js|qs)[\\/]/,
            chunks: 'all',
            priority: 1,
            reuseExistingChunk: true,
            enforce: true
          },
        }
      }
    },
    plugins: [
      ...generateDllReferences(),
      new AddAssetHtmlPlugin({ 
        filepath: require.resolve('./public/assets/dll/_frame.js'),
        outputPath: '/assets/dll', // 输出路径
        publicPath: '/assets/dll' // 插入html的拼接路径
      }),
    ],
  }
}
